<template>
<view>
<view v-if="active.active_id" class="container">
  <!-- 自定义标题栏 -->
  <navigationBar title="商品详情" extClass="nav" id="top"></navigationBar>
  <!-- 富文本组件 -->
  

  <!-- 滚动容器 -->
  <scroll-view class="scroll-container" @scroll="onScrollEvent" :scroll-top="scrollTop" scroll-y="true">

    <!-- 商品图片 -->
	  <detail-swiper :imageList="goods.goods.image"></detail-swiper>
    <!-- 价格、倒计时 top-->
    <view class="info-item info-item__top dis-flex flex-x-between flex-y-center">
      <image lazy-load src="/static/images/kanjia_bg.png" style="position:absolute;top:0;left:0;width:100%;height:100%;z-index:-1;"></image>
      <view class="block-left dis-flex flex-y-center">
        <!-- 底价 -->
        <text class="floor-price__samll">￥</text>
        <text class="floor-price">{{ active.floor_price }}</text>
        <!-- 原价 -->
        <text class="original-price">￥{{ goods.goods.goods_sku.goods_price }}</text>
      </view>
      <!-- 活动倒计时 -->
      <view v-if="!active.is_end" class="info-item info-item_status info-item_countdown">
        <view>距离结束</view>
        <block v-for="(item, index) in actEndTimeList" :key="index">
          <view class="countdown"><text>{{ item.dynamic.hou }}</text>:<text>{{ item.dynamic.min }}</text>:<text>{{ item.dynamic.sec }}</text></view>
        </block>
      </view>
      <!-- 活动已结束 -->
      <view v-if="active.is_end" class="info-item info-item_status info-item_end f-32">
        <text>活动已结束</text>
      </view>
    </view>
    <view class="main">
      <!-- 商品信息 -->
      <view class="goods-info">
        <!-- 标题、分享 -->
        <view class="info-item info-item__name">
          <view class="goods-name flex-box twolist-hidden">
            <text class="active-tag">限时砍价</text>
            <text >{{ goods.goods.goods_name }}</text>
          </view>
          
          <view class="block-right dis-flex flex-y-center flex-x-between m-t-20">
            <!-- 销量 -->
            <view class="goods-sales">
              <text>{{ active.active_sales }}人已砍成</text>
            </view>
            <!-- 分享 -->
            <view class="goods-share">
              <form @submit="onClickShare" report-submit="true">
                <button formType="submit" class="share-btn dis-flex flex-dir-column">
                  <text class="share__icon iconfont2 icon-share"></text>
                  <text class="f-24">分享</text>
                </button>
              </form>
            </view>
          </view>
					<!-- 标签 -->
					<view class="tag-wrap dis-flex flex-wrap">
						<view class="f-24 m-r-10" v-for="(item,index) in goods.goods.tags" :key="index">#{{item}}</view>
					</view>
        </view>
      </view>
			<view class="gray-bg20"></view>

      <!-- 砍价玩法 -->
      <view class="bargain-rules top-nav-bar b-f">
        <form @submit="onToggleRules" report-submit="true">
          <button formType="submit" class="btn-normal">

            <view class="item-title dis-flex flex-y-center">
              <view class="block-left flex-box f-28 col-0">
                <text>砍价玩法</text>
              </view>
              <view class="block-right">
                <text class="show-more col-9 f-24">查看规则</text>
              </view>
            </view>

            <!-- 砍价步骤 -->
            <view class="rule-simple dis-flex flex-x-around">
                <view class="simple-item dis-flex flex-dir-column flex-y-center">
                  <view class="i-number dis-flex flex-x-center flex-y-center">
                    <view class="i-inner"></view>
                    <view class="i-line"></view>
                  </view>
                  <view class="i-text f-24 col-3">点击砍价</view>
                </view>
                <view class="simple-item dis-flex flex-dir-column flex-y-center">
                  <view class="i-number dis-flex flex-x-center flex-y-center">
                    <view class="i-line"></view>
                  </view>
                  <view class="i-text f-24 col-9">找人帮砍</view>
                </view>
                <view class="simple-item dis-flex flex-dir-column flex-y-center">
                  <view class="i-number dis-flex flex-x-center flex-y-center">
                    <view class="i-line"></view>
                  </view>
                  <view class="i-text f-24 col-9">砍到最低</view>
                </view>
                <view class="simple-item dis-flex flex-dir-column flex-y-center">
                  <view class="i-number dis-flex flex-x-center flex-y-center">
                  </view>
                  <view class="i-text f-24 col-9">优惠购买</view>
                </view>
              </view>
          </button>
        </form>
      </view>
			<view class="gray-bg20"></view>
			<!-- 卖点 -->
			<selling-point :selling_point="detail.selling_point"></selling-point>
      <!-- 商品评价 -->
      <goods-comment :comment_data="goods.comment_data" :comment_data_count="goods.comment_data_count" :goods_id="goods.wxapp_goods_id"></goods-comment>
			<view class="gray-bg20"></view>
      <!-- 商品描述 -->
      <goods-describe :article_content="article_content"></goods-describe>
			<!-- 购前说明 -->
			<goods-instructions></goods-instructions>
			<!-- 谁购买了 -->
			<goods-buyers :buyerList="buy_user" :goods_id="goods.wxapp_goods_id"></goods-buyers>
			<!-- 猜你喜欢 -->
			<goods-like :goodsLikeList="list.data"></goods-like>
    </view>
  </scroll-view>

  <!-- 底部选项卡 -->
  <view class="footer-fixed">
    <view class="footer-container dis-flex">
      <!-- 导航图标 -->
      <view class="foo-item-fast dis-flex flex-x-center flex-y-center">
        <form @submit="onTargetHome" report-submit>
          <button class="btn-normal" formType="submit">
            <view class="fast-item fast-item_home">
              <text class="iconfont2 icon-Fill1 fast-icon"></text>
              <view class="fast-text">
                <text>首页</text>
              </view>
            </view>
          </button>
        </form>
				<!-- 在线客服 -->
				<button class="btn-normal" @tap="upload(goods.goods.image)">
					<view class="fast-item fast-item_home" style="margin-right: 0;">
						<!-- <text class="iconfont2 icon-kefu fast-icon"></text>
						<view class="fast-text">
							<text>客服</text>
						</view> -->
						<text class="iconfont2 icon-download fast-icon"></text>
						<view class="fast-text">
							<text>下载</text>
						</view>
					</view>
				</button>
      </view>
      <!-- 操作按钮 -->
      <view class="foo-item-trigger flex-box">
        <form @submit="openDialog('buyNow')" report-submit>
          <button v-if="active.is_start && !active.is_end" class="opt-btn btn-main btn-normal" formType="submit">
            <text>{{ is_partake ? '继续砍价' : '立即砍价' }}</text>
          </button>
          <button v-else class="opt-btn btn-gray btn-normal">
            <text>{{ active.is_end ? '活动已结束' : '活动未开启' }}</text>
          </button>
        </form>
      </view>
    </view>
  </view>

	<!-- 确认购买弹窗 -->
	<proSpecs ref="proSpecs"></proSpecs>


  <!-- 砍价规则 -->
  <zan-dialog id="zan-base-dialog"></zan-dialog>

  <!-- 快捷导航 -->
  <shortcut bottom="120rpx"></shortcut>

  <!-- 返回顶部 -->
  <view @tap.stop="onScrollTop" class="widget-goTop" v-if="showTopWidget">
    <text class="iconfont icon-fanhuidingbu"></text>
  </view>
	<download-file @comfirmStatus="comfirmStatusS" ref="download"></download-file>
	<share-bottom ref="shareBottom" pageType="bargin"></share-bottom>

</view>
</view>
</template>

<script>
const app = getApp().globalData; // 富文本插件
// 工具类
import util from "../../../utils/util"; // 倒计时插件
// 倒计时插件
import CountDown from "../../../utils/countdown"; // 对话框插件
// 对话框插件
import Dialog from '@/components/dialog/dialog'; // 记录规格的数组
// 记录规格的数组
let goodsSpecArr = [];
import zanDialog from "@/components/dialog/index";
import zanPopup from "@/components/popup/index";
import shortcut from "@/components/shortcut/shortcut";
import detailSwiper from '@/components/goods/detail-swiper/index';
import goodsComment from '@/components/goods/goods-comment/index';
import goodsDescribe from '@/components/goods/goods-describe/index';
import sellingPoint from '@/components/goods/selling-point/index';
import goodsBuyers from '@/components/goods/goods-buyers/index';
import goodsInstructions from '@/components/goods/goods-instructions/index';
import goodsLike from '@/components/goods/goods-like/index';
import downloadFile from '@/components/download-file';
import shareBottom from '@/components/share-bottom/index';
import proSpecs from '../proSpecs/pro-specs';

export default {
  components: {
    zanPopup,
		zanDialog,
    shortcut,
	  detailSwiper,
    goodsComment,
    goodsDescribe,
		sellingPoint,
		goodsBuyers,
		goodsInstructions,
		goodsLike,
		downloadFile,
		shareBottom,
		proSpecs
  },
  data() {
    return {
      // 轮播图指针
      floorstatus: false,
      // 返回顶部
      detail: {},
      // 商品详情信息
      goods_price: 0,
      // 商品价格
      line_price: 0,
      // 划线价格
      stock_num: 0,
      // 库存数量
      // goods_num: 1,
      // 商品数量
      goods_sku_id: 0,
      // 规格id
      cart_total_num: 0,
      // 购物车商品总数量
      goodsMultiSpec: {},
      // 多规格信息\
      // 返回顶部
      showTopWidget: false,
      // 倒计时
      actEndTimeList: [],
      active: {},
      // 砍价活动详情
      goods: {},
      // 商品详情
      setting: {},
      // 砍价配置
      is_partake: false,
      // 当前用户是否正在参与
      task_id: false // 当前用户正在参与的任务id
      ,
      active_id: "",
      skuCoverImage: "",
      scrollTop: 0,
      article_content: "",
			
			buy_user: [],//谁购买了
			// 猜你喜欢
			list: '',//信息
			page: 1,
			loadding: false,
			pullUpOn: true,
    };
  },

  props: {},

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
		//切换店铺
		if (options.wid) {
			app.wxapp_id = options.wid;
			wx.setStorageSync("wxapp_id", options.wid)
		}
		
    let that = this,
        scene = app.getSceneData(options); 
				// 砍价商品id
    that.active_id = options.active_id ? options.active_id : scene.aid
		
		if (scene.wid) {
			app.wxapp_id = scene.wid;
			wx.setStorageSync("wxapp_id", scene.wid)
		}

		// #ifdef MP
		wx.showShareMenu({
			menus: ['shareAppMessage', 'shareTimeline'],
			success(res) {},
			fail(e) {}
		})
		// #endif
		
		// 猜你喜欢
		that.page = 1;
		that.list = '';
		that.loadding= false;
		that.pullUpOn= true;
		that.getLikes()
  },
	// 上拉加载下一页
	onReachBottom () {
		let that = this;
		if (!that.pullUpOn) return;
			that.loadding = true;
		if (that.page >= that.list.last_page) {
			that.loadding = false;
			that.pullUpOn = false;
		} else {
			that.page = ++that.page;
			that.loadding = false;
			that.getLikes();
		}
	},
	// 设置菜单中的转发按钮触发转发事件时的转发内容
	// #ifdef MP
	onShareAppMessage (res) {
		let shareObj = {      
			title: this.goods.goods.goods_name,
			path: '/pages/bargain/goods/index?active_id='+this.active_id +'&wid=' + this.goods.wxapp_id,
		};
		return shareObj;
	},
	onShareTimeline(){
		return {
			title: this.goods.goods.goods_name,
			query: 'active_id='+ this.active_id +'&wid=' + this.goods.wxapp_id,
		};
	},
	// #endif
  /**
   * 生命周期函数--监听页面显示
   */
  onShow(options) {
    let _this = this; // 获取砍价商品信息


    _this.getActiveDetail();
  },

  methods: {
		//猜你喜欢
		getLikes(){
			let data = {
				page: this.page,
				sortType: 'recommend',
				shop_rmd: 1
			};
			app._get('wxapp.goods/lists', data, res => {
				let _list = this.list;
				let data = res.data.list;
				if(this.page==1){
					_list = data;
				}else{
					_list.data = _list.data.concat(data.data);
				}
				this.list = _list;
			})
		},
    /**
     * 获取砍价商品信息
     */
    getActiveDetail() {
      let _this = this;

      getApp().globalData._get('bargain.active/detail', {
        active_id: _this.active_id
      }, result => {
				// 谁购买了
				this.buy_user = result.data.buy_user || [];
        // 初始化详情数据
        let data = _this.initDataFun(result.data);
        _this.setData(data); // 执行倒计时
				

        if (!data.active.is_end) {
          CountDown.onSetTimeList(_this, 'actEndTimeList');
        }
      }, result => {
        _this.back();
      });
    },

    back: function back() {
      var data = this;
      console.log(data);
      wx.navigateBack({
        delta: data.delta
      });
      this.$emit('back', {
        delta: data.delta
      }, {});
    },

    /**
     * 初始化详情数据
     */
    initDataFun(data) {
      let _this = this; // 商品详情


      let goodsDetail = data.goods.goods; // 富文本转码
			
      if (goodsDetail.content.length > 0) {
        setTimeout(() => {
          _this.article_content = goodsDetail.content;
        }, 200);
      } 

			// 商品价格/划线价/库存
      data.goods_sku_id = goodsDetail.goods_sku.spec_sku_id;
      data.goods_price = goodsDetail.goods_sku.goods_price;
      data.line_price = goodsDetail.goods_sku.line_price;
      data.stock_num = goodsDetail.goods_sku.stock_num; // 商品封面图(确认弹窗)

      data.skuCoverImage = goodsDetail.goods_image; // 多规格商品封面图(确认弹窗)

      if (goodsDetail.spec_type == 20 && goodsDetail.goods_sku['image']) {
        data.skuCoverImage = goodsDetail.goods_sku['image']['file_path'];
      } // 商品图片列表将视频放在首位


      if (goodsDetail.image) {
        data.goods.image = _this.initImageList(goodsDetail.image);
      } // 初始化商品多规格


      if (goodsDetail.spec_type == 20) {
        data.goodsMultiSpec = _this.initManySpecDataFun(goodsDetail.goods_multi_spec);
      } // 商品评价时间截取


      if (goodsDetail.comment_data_count > 0) {
        data.comment_data = _this.initCommentDataFun(goodsDetail.comment_data);
      } // 记录活动到期时间


      data.actEndTimeList = [{
        date: data.active.end_time
      }];
      return data;
    },

    // 初始化图片列表
    initImageList(data) {
      let newData = [];
      data.forEach(item => {
        if (item.file_type == 'video') {
          newData.push(item);
        }
      });
      data.forEach(item => {
        if (item.file_type == 'image') {
          newData.push(item);
        }
      });
      return newData;
    },
    /**
     * 初始化商品多规格
     */
    initManySpecDataFun(data) {
      goodsSpecArr = [];

      for (let i in data.spec_attr) {
        for (let j in data.spec_attr[i].spec_items) {
          if (j < 1) {
            data.spec_attr[i].spec_items[0].checked = true;
            goodsSpecArr[i] = data.spec_attr[i].spec_items[0].item_id;
          }
        }
      }

      return data;
    },

    /**
      * 初始化评论时间
      */
    initCommentDataFun(data) {
      console.log(data);

      for (let i = 0; i < data.length; i++) {
        if (data[i].create_time) {
          data[i].create_newtime = data[i].create_time.substring(5, 16);
        }
      }

      return data;
    },

    /**
     * 跳转到评论
     */
    onTargetToComment() {
      let _this = this;

      uni.navigateTo({
        url: `../../goods/comment/comment?goods_id=${_this.goods.goods_id}`
      });
    },

    /**
     * 返回顶部
     */
    onScrollTop(t) {
      let _this = this;

      _this.setData({
        scrollTop: 0
      });
    },

    /**
     * 显示/隐藏 返回顶部按钮
     */
    onScrollEvent(e) {
      let _this = this;

      _this.setData({
        showTopWidget: e.detail.scrollTop > 200
      });
    },

    /**
     * 显示分享选项
     */
    onClickShare(e) {
			let goods = this.goods;
			goods.active_id = this.active.active_id;
			let data = {
				opeText: 'weChat, weChatFriends',
				isTwo: true,
				upGoods: goods
			}
			this.$refs.shareBottom.open(data);
    },

    /**
     * 显示砍价规则
     */
    onToggleRules(e) {
      // 记录formId
      getApp().globalData.saveFormId(e.detail.formId); // 显示砍价规则

      let _this = this;

      Dialog({
        title: '砍价规则',
        message: _this.setting.bargain_rules,
        selector: '#zan-base-dialog',
        isScroll: true,
        // 滚动
        buttons: [{
          text: '关闭',
          color: 'red',
          type: 'cash'
        }]
      });
    },
		
		openDialog(btnType) {
			let goods = this.goods;
			goods.active_id = this.active.active_id;
			goods.floor_price = this.active.floor_price;
			this.$refs.proSpecs._open(goods,btnType||'')
		},
    /**
     * 确认砍价
     */
    onSubmit(e) {
      let _this = this; // 记录formId
			
      getApp().globalData.saveFormId(e.detail.formId); 
			// 判断是否已参与当前的砍价活动，如果已参与的话跳转到砍价任务

      if (_this.is_partake) {
        uni.navigateTo({
          url: `../task/index?task_id=${_this.task_id}`
        });
        return;
      } // 多规格商品，弹出选择器

      if (_this.goods.goods.spec_type == 20) {
        _this.onToggleTrade();

        return;
      } // 确认发起砍价


      _this.onCheckout();
    },

    /**
     * 跳转到首页
     */
    onTargetHome(e) {
      // 记录formid
      getApp().globalData.saveFormId(e.detail.formId);
      uni.navigateTo({
        url: '../../index/index'
      });
    },
		// 点击下载
		upload(files){
			const that = this;
			let uploads = [];
			files.forEach(item => {
				uploads.push(item.file_path)
			});
			if(uploads!=''){
				uni.showModal({
					title: '友情提示',
					content: '是否下载该商品的图片/视频？',
					confirmColor: '#E82E2E',
					confirmText: '是',
					cancelText: '否',
					success: (res) => {
						if(res.confirm){
							that.$refs.download._downloadFileS(uploads);
						}
					}
				});
			}else{
				that.$api.msg('该商品暂无可下载的图片/视频');
			}
		},
		//下载回调
		comfirmStatusS (promise) {
			promise.then((res) => {
				uni.hideLoading();
				uni.hideToast();
				this.$api.msg(res?"保存成功~":'取消保存')
			})
		},

  }
};
</script>
<style lang="scss" scoped>
	@import "index";
</style>